package cn.edu.scau.dormitory_management_system.util;

import cn.edu.scau.dormitory_management_system.constant.FilePath;
import cn.edu.scau.dormitory_management_system.exception.pojo.MyException;
import cn.edu.scau.dormitory_management_system.enums.ExceptionMsgEnum;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author djc
 * @date 2021/8/8
 * @time 16:00
 */
public class FileUtil {
    public static void deleteFile(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        assert files != null;
        for (File subFile : files) {
            subFile.delete();
        }
    }

    public static void downloadFile(HttpServletResponse response,
                                    File file,
                                    String fileName) {
        try {
            if(fileName.endsWith(".zip")) response.setContentType("application/zip;charset=utf-8");
            else response.setContentType("application/vnd.ms-excel;charset=utf-8");

            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            String absolutePath = file.getAbsolutePath();

            InputStream is = new FileInputStream(absolutePath);

            BufferedInputStream bis = new BufferedInputStream(is);
            int length;
            byte[] temp = new byte[1024 * 10];
            while ((length = bis.read(temp)) != -1) {
                bos.write(temp, 0, length);
            }
            bos.flush();
            bis.close();
            bos.close();
            is.close();
        }catch (Exception ex) {
            deleteFile(FilePath.TEMP_PATH);
            deleteFile(FilePath.ZIP_PATH);
            throw new MyException(ExceptionMsgEnum.EXPORT_FAILURE);
        }
    }
}
